package com.iqismart.shorturl.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.iqismart.shorturl.cache.UrlCountCache;
import com.iqismart.shorturl.config.UidHolder;
import com.iqismart.shorturl.exception.BaseException;
import com.iqismart.shorturl.model.EntityUser;
import com.iqismart.shorturl.repository.UserRepository;
import com.iqismart.shorturl.service.UserService;
import com.iqismart.shorturl.utils.PasswordEncoder;
import com.iqismart.shorturl.utils.UserTokenUtils;
import com.iqismart.shorturl.vo.*;
import com.iqismart.shorturl.websocket.MyWebSocket;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description
 * @Auther sty
 * @createTime 2019-10-15 15:19
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository userRepository;

    @Override
    public LoginResponse login(LoginRequest request) {
        if(StringUtils.isEmpty(request.getUsername())){
            BaseException.failAndThrow("用户名不能为空");
        }
        if(StringUtils.isEmpty(request.getPassword())){
            BaseException.failAndThrow("密码不能为空");
        }
        EntityUser entityUser = userRepository.findByUsername(request.getUsername());
        if(entityUser==null){
            BaseException.failAndThrow("用户不存在");
        }

        if(!PasswordEncoder.pass(request.getPassword(),entityUser.getPassword())){
            BaseException.failAndThrow("密码不正确");
        }


        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("type","login");
            jsonObject.put("uid",entityUser.getId());
            jsonObject.put("nickname",entityUser.getNickname());
            MyWebSocket.sendMessageToAll(jsonObject.toJSONString());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return getLoginResponse(entityUser);
    }

    @Override
    public LoginResponse register(RegisterRequest request) {
        if(StringUtils.isEmpty(request.getUsername())){
            BaseException.failAndThrow("用户名不能为空");
        }

        EntityUser entityUser = userRepository.findByUsername(request.getUsername());
        if(entityUser != null){
            BaseException.failAndThrow("用户已存在");
        }

        if(StringUtils.isEmpty(request.getPassword())){
            BaseException.failAndThrow("密码不能为空");
        }
        if(StringUtils.isEmpty(request.getPasswordConfirm())){
            BaseException.failAndThrow("确认密码不能为空");
        }
        if(!request.getPasswordConfirm().equals(request.getPassword())){
            BaseException.failAndThrow("两次密码不一致");
        }

        entityUser = new EntityUser();
        entityUser.setUsername(request.getUsername());
        entityUser.setPassword(PasswordEncoder.encode(request.getPassword()));
        entityUser = userRepository.save(entityUser);

        UrlCountCache.map.put("newUid",entityUser.getId()+"");
        UrlCountCache.map.put("newUsername",entityUser.getUsername()+"");

        return getLoginResponse(entityUser);
    }

    private LoginResponse getLoginResponse(EntityUser entityUser) {
        String token = UserTokenUtils.encode(entityUser.getId());
        final LoginResponse loginResponse = new LoginResponse();
        BeanUtils.copyProperties(entityUser, loginResponse);
        loginResponse.setToken(token);
        return loginResponse;
    }

    @Override
    public void userInfo(UserInfoRequest request) {
        Long uid = UidHolder.mustUid();
        EntityUser entityUser =  userRepository.findById(uid).get();
        entityUser.setNickname(request.getNickname());
        entityUser.setMobile(request.getMobile());
        userRepository.save(entityUser);
    }

    @Override
    public void resetPassword(ResetPasswordRequest request) {
        Long uid = UidHolder.mustUid();
        if(StringUtils.isEmpty(request.getNewPassword())){
            BaseException.failAndThrow("密码不能为空");
        }
        EntityUser entityUser =  userRepository.findById(uid).get();
        entityUser.setPassword(PasswordEncoder.encode(request.getNewPassword()));
        userRepository.save(entityUser);
    }

    @Override
    public String apiKey() {
        Long uid = UidHolder.mustUid();
        return UserTokenUtils.encode(uid);
    }

    @Override
    public UserInfoResponse getUserInfo() {
        try {
            Long uid = UidHolder.mustUid();
            EntityUser entityUser =  userRepository.findById(uid).get();

            return entityUser.toResponse();
        } catch (Exception e) {
            BaseException.failAndThrow("用户信息不存在");
        }
        return  null;
    }

    @Override
    public List<UserInfoResponse> getNewUserList() {
        return getNewUserList(10);
    }

    @Override
    public List<UserInfoResponse> getNewUserList(int count) {
        final List<EntityUser> content = userRepository.findAll((Specification<EntityUser>) (root, cq, cb) -> {
            return cb.and(cb.greaterThan(root.get("id"), 0));
        }, PageRequest.of(0, count, Sort.Direction.DESC, "id")).getContent();
        List<UserInfoResponse> responses = new ArrayList<>();
        content.forEach(u->responses.add(u.toResponse()));
        return responses;
    }


}
